package com.joey.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Author hyy
 **/
@Slf4j
public class SemaphoreExample {

    private static final int threadCount = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount/50);

        for (int i=0;i<threadCount;i++){
            final int threadNum = i;
            executorService.execute(()->{
                try {
                    //获取许可
//                    semaphore.acquire(4);
                    semaphore.acquire();
                    test(threadNum);
                    //释放许可
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception",e);
                }
            });
        }
        //

        log.info("finish");
        executorService.shutdown();

    }

    private static void test(int threadCount) throws InterruptedException {
        Thread.sleep(1000);
        log.info("threadCount:{}",threadCount);
    }




}
